

#include "EditOperator.h"
#include "Node.h"

EditOperator::EditOperator(QWidget * parent)
: QLineEdit(parent) {
    connect(this, SIGNAL(textChanged(QString)),
            this, SLOT(upDateSize()));

    // set background & border
    setStyleSheet("background: transparent; border: none");

    // resize the input field
    upDateSize();
}

void EditOperator::keyPressEvent(QKeyEvent *event) {
//    QLineEdit::keyPressEvent(event);

        if (event->text().contains(QRegExp("[+\\-/^*()=,%]"))
                or (event->key() == Qt::Key_Backspace)// and textNotChanged)
                or (event->key() == Qt::Key_Delete)// and textNotChanged)
                or (event->key() == Qt::Key_Right)// and cursorNotMoved)
                or (event->key() == Qt::Key_Left) ){// and cursorNotMoved)
            event->ignore();
        } else {
            event->accept();
        }
}

QSize EditOperator::sizeHint() const {
    QSize bsize = QLineEdit::sizeHint();
    QFontMetrics fm(font());

    // find what QLineEdit::sizeHint() added to base size for frame
    // by see how much it added to its base calculation.
    int width = bsize.width() - fm.width(QLatin1Char('x')) * 17;

    // add to that the width needed by the content
    width += fm.width(text());

    bsize.setWidth(width);

    return bsize;
}

void EditOperator::upDateSize() {
    adjustSize();
    updateGeometry();

    setMaximumSize(sizeHint());
    Node *nodeParent = qobject_cast<Node *>(parent());
    if (nodeParent) {
        nodeParent->upDateSize();
    }
}